<template>
	<div class="provider-config-modal" v-if="visible" @click.self="closeModal">
		<div class="modal-content">
			<div class="modal-header">
				<h3>供应商配置</h3>
				<button class="close-btn" @click="closeModal">×</button>
			</div>

			<div class="modal-body">
				<!-- 左侧供应商列表 -->
				<div class="provider-list">
					<div
						class="provider-item"
						v-for="provider in providers"
						:key="provider.id"
						:class="{ active: selectedProvider?.id === provider.id }"
						@click="selectProvider(provider)"
					>
						<span class="provider-name">{{ provider.name }}</span>
						<span v-if="provider.enabled" class="provider-status on"> on </span>
					</div>
				</div>

				<!-- 右侧详情表单 -->
				<div class="provider-details" v-if="selectedProvider">
					<div class="provider-header">
						<span class="title">{{ selectedProvider.name }}</span>
						<label class="switch" :class="{ loading: isSwitchLoading }">
							<input
								type="checkbox"
								v-model="selectedProvider.enabled"
								@change="toggleProviderStatus"
								:disabled="isSwitchLoading"
							/>
							<span class="slider"></span>
						</label>
					</div>

					<form>
						<!-- <div class="form-group">
							<label><span class="required">*</span>API Host</label>
							<input
								type="text"
								v-model="selectedProvider.apiHost"
								:class="['form-input', { error: validationErrors.apiHost }]"
								placeholder="请输入API Host"
							/>
							<span v-if="validationErrors.apiHost" class="error-message">{{
								validationErrors.apiHost
							}}</span>
						</div> -->

						<div class="form-group">
							<label>API Key <span class="required">*</span></label>
							<input
								type="password"
								v-model="selectedProvider.apiKey"
								:class="['form-input', { error: validationErrors.apiKey }]"
								placeholder="请输入API Key"
							/>
							<span v-if="validationErrors.apiKey" class="error-message">{{
								validationErrors.apiKey
							}}</span>
						</div>
					</form>
				</div>
			</div>
		</div>
	</div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from "vue";
import { useAiCore } from "../AiCore/index";
import type { Provider } from "../AiCore/AiCore";

const props = defineProps<{
	visible: boolean;
}>();

const emit = defineEmits<{
	"update:visible": [value: boolean];
	save: [];
}>();

const aiCore = useAiCore();
const providers = ref<Provider[]>([]);
const selectedProviderId = ref<string>("");
const validationErrors = ref<Record<string, string>>({});
const isSwitchLoading = ref(false);

// 初始化数据
onMounted(() => {
	loadProviders();
});

// 监听visible变化，重新加载数据
watch(
	() => props.visible,
	(newVisible) => {
		if (newVisible) {
			loadProviders();
		}
	}
);

const loadProviders = () => {
	providers.value = JSON.parse(JSON.stringify(aiCore.providers));

	// 设置默认选中的供应商
	if (providers.value.length > 0) {
		const enabledProvider = providers.value.find((p) => p.enabled);
		selectedProviderId.value = enabledProvider?.id || providers.value[0].id;
	}
};

const selectedProvider = computed(() =>
	providers.value.find((p) => p.id === selectedProviderId.value)
);

const selectProvider = (provider: Provider) => {
	selectedProviderId.value = provider.id;
	validationErrors.value = {}; // 切换供应商时清除错误
};

const validateProvider = () => {
	if (!selectedProvider.value) return false;

	validationErrors.value = {};
	let hasError = false;

	// 验证API Host
	if (
		!selectedProvider.value.apiHost ||
		!selectedProvider.value.apiHost.trim()
	) {
		validationErrors.value.apiHost = "API Host不能为空";
		hasError = true;
	} else if (!selectedProvider.value.apiHost.trim()) {
		validationErrors.value.apiHost = "API Host不能全为空格";
		hasError = true;
	}

	// 验证API Key
	if (!selectedProvider.value.apiKey || !selectedProvider.value.apiKey.trim()) {
		validationErrors.value.apiKey = "API Key不能为空";
		hasError = true;
	} else if (!selectedProvider.value.apiKey.trim()) {
		validationErrors.value.apiKey = "API Key不能全为空格";
		hasError = true;
	}

	return !hasError;
};

const showMessage = (
	message: string,
	type: "success" | "warning" | "error" = "success"
) => {
	const messageEl = document.createElement("div");
	messageEl.className = `message-toast ${type}`;
	messageEl.textContent = message;
	messageEl.style.cssText = `
		position: fixed;
		top: 20px;
		right: 20px;
		padding: 12px 20px;
		border-radius: 4px;
		color: white;
		font-size: 14px;
		z-index: 9999;
		box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
		animation: slideIn 0.3s ease;
	`;
	if (type === "success") {
		messageEl.style.backgroundColor = "#67c23a";
	} else if (type === "warning") {
		messageEl.style.backgroundColor = "#e6a23c";
	} else {
		messageEl.style.backgroundColor = "#f56c6c";
	}
	document.body.appendChild(messageEl);
	setTimeout(() => {
		messageEl.style.animation = "slideOut 0.3s ease";
		setTimeout(() => messageEl.remove?.(), 300);
	}, 3000);
};

const toggleProviderStatus = async () => {
	if (!selectedProvider.value) return;

	if (selectedProvider.value.enabled) {
		if (!validateProvider()) {
			selectedProvider.value.enabled = false;
			return;
		}
		isSwitchLoading.value = true;

		try {
			const providerCopy = JSON.parse(JSON.stringify(selectedProvider.value));
			const isValid = await aiCore.verifyApiKey(providerCopy);
			if (isValid) {
				selectedProvider.value.enabled = true;
				showMessage("API Key验证成功，供应商已启用", "success");
			} else {
				selectedProvider.value.enabled = false;
				showMessage("API Key验证失败，供应商已禁用", "warning");
			}
		} catch (error) {
			selectedProvider.value.enabled = false;
			showMessage("验证过程中发生错误，供应商已禁用", "error");
		} finally {
			isSwitchLoading.value = false;
		}
	}
	const providerCopy = JSON.parse(JSON.stringify(selectedProvider.value));
	aiCore.updateProvider(providerCopy);
	emit("save");
};
// const saveProvider = () => {
// 	// 更新AiCore中的配置
// 	providers.value.forEach((provider) => {
// 		aiCore.updateProvider(provider);
// 	});

// 	// 保存到本地存储
// 	aiCore.saveToStorage();

// 	emit("save", [...providers.value]);
// 	closeModal();
// };

const closeModal = () => {
	emit("update:visible", false);
};
</script>

<style scoped lang="scss">
.provider-config-modal {
	position: fixed;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	background-color: rgba(0, 0, 0, 0.5);
	display: flex;
	align-items: center;
	justify-content: center;
	z-index: 1000;
}

.modal-content {
	background: var(--color-background);
	border-radius: 8px;
	width: 95%;
	max-height: 90vh;
	overflow: hidden;
	box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.modal-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 16px 20px;
	border-bottom: 1px solid var(--color-border);

	h3 {
		margin: 0;
		font-size: 18px;
		font-weight: 600;
	}

	.close-btn {
		background: none;
		border: none;
		font-size: 24px;
		cursor: pointer;
		color: var(--color-text-secondary);

		&:hover {
			color: var(--color-text);
		}
	}
}

.modal-body {
	display: flex;
	height: 500px;
}

.provider-list {
	width: 120px;
	border-right: 1px solid var(--color-border);
	overflow-y: auto;

	h4 {
		margin: 0 0 12px 0;
		font-size: 13px;
		font-weight: 600;
		color: var(--color-text-secondary);
		text-align: center;
	}

	.provider-item {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 8px 12px;
		margin-bottom: 6px;
		cursor: pointer;
		transition: background-color 0.2s;
		font-size: 12px;

		&:hover {
			background-color: var(--color-background-soft);
		}

		&.active {
			background-color: var(--color-primary);
			color: white;
			.provider-status {
				color: white;
			}
		}

		.provider-name {
			font-weight: 500;
			word-break: break-word;
			line-height: 1.2;
		}

		.provider-status {
			font-size: 10px;
			color: var(--color-primary);
			font-weight: 600;
		}
	}
}

.provider-details {
	flex: 1;
	padding: 12px;
	overflow-y: auto;

	.provider-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 0 0 12px 0;
		.title {
			margin: 0;
			font-size: 16px;
			font-weight: 800;
		}
	}
}

.form-group {
	margin-bottom: 12px;

	label {
		display: block;
		margin-bottom: 6px;
		font-weight: 500;
		font-size: 13px;
		.required {
			color: red;
		}
	}

	.form-input {
		width: 100%;
		padding: 6px 10px;
		border: 1px solid var(--color-border);
		border-radius: 4px;
		font-size: 13px;
		background: var(--color-background-soft);

		&:focus {
			outline: none;
			border-color: var(--color-primary);
		}

		&.error {
			border-color: var(--color-error);
		}

		&.model-name {
			width: 35%;
		}

		&.model-id {
			width: 45%;
		}
	}

	.error-message {
		color: var(--color-error);
		font-size: 12px;
		margin-top: 4px;
		display: block;
	}
}

.switch {
	position: relative;
	display: inline-block;
	width: 44px;
	height: 24px;

	input {
		opacity: 0;
		width: 0;
		height: 0;
	}

	.slider {
		position: absolute;
		cursor: pointer;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: var(--color-border);
		transition: 0.3s;
		border-radius: 24px;

		&:before {
			position: absolute;
			content: "";
			height: 18px;
			width: 18px;
			left: 3px;
			bottom: 3px;
			background-color: white;
			transition: 0.3s;
			border-radius: 50%;
		}
	}

	input:checked + .slider {
		background-color: var(--color-primary);
	}

	input:checked + .slider:before {
		transform: translateX(20px);
	}
}

.models-list {
	.model-item {
		margin-bottom: 8px;

		.model-info {
			display: flex;
			gap: 4px;
			align-items: center;
		}
	}

	.add-btn {
		background: none;
		border: 1px dashed var(--color-border);
		padding: 6px 12px;
		border-radius: 4px;
		cursor: pointer;
		color: var(--color-primary);
		font-size: 12px;
		width: 100%;

		&:hover {
			background-color: var(--color-background-soft);
		}
	}
}

.delete-btn {
	background: none;
	border: none;
	color: var(--color-error);
	font-size: 16px;
	cursor: pointer;
	padding: 2px;
	width: 20px;
	height: 20px;
	display: flex;
	align-items: center;
	justify-content: center;

	&:hover {
		background-color: var(--color-background-soft);
		border-radius: 2px;
	}
}

.form-actions {
	display: flex;
	gap: 8px;
	justify-content: flex-end;
	margin-top: 16px;
	padding-top: 12px;
	border-top: 1px solid var(--color-border);
}

.btn {
	padding: 6px 12px;
	border-radius: 4px;
	font-size: 12px;
	cursor: pointer;
	border: none;

	&.btn-primary {
		background-color: var(--color-primary);
		color: white;

		&:hover {
			background-color: var(--color-primary-hover);
		}
	}

	&.btn-secondary {
		background-color: var(--color-background-soft);
		color: var(--color-text);
		border: 1px solid var(--color-border);

		&:hover {
			background-color: var(--color-border);
		}
	}
}

/* Switch loading状态样式 */
.switch.loading {
	opacity: 0.6;
	cursor: not-allowed;

	.slider {
		position: relative;

		&::after {
			content: "";
			position: absolute;
			top: 50%;
			left: 50%;
			width: 20px;
			height: 20px;
			margin: -10px 0 0 -10px;
			border: 2px solid var(--color-border);
			border-top-color: white;
			border-radius: 50%;
			animation: spin 1s linear infinite;
		}
	}
}

/* 消息提示动画 */
@keyframes slideIn {
	from {
		opacity: 0;
		transform: translateX(100%);
	}
	to {
		opacity: 1;
		transform: translateX(0);
	}
}

@keyframes slideOut {
	from {
		opacity: 1;
		transform: translateX(0);
	}
	to {
		opacity: 0;
		transform: translateX(100%);
	}
}

@keyframes spin {
	from {
		transform: rotate(0deg);
	}
	to {
		transform: rotate(360deg);
	}
}
</style>
